<template>
  <view class="container">
    <!-- 项目信息模块 -->
    <view class="partitem">
      <view class="project-item">
        <h3>项目信息</h3>
      </view>

      <!-- 选择项目：搜索框 + 下拉筛选 -->
      <view class="partname">
        <text>选择项目</text>
        <view class="select-container">
          <!-- 搜索框 -->
          <input type="text" v-model="searchKeyword" placeholder="请输入项目名称搜索" class="inputstyle" @focus="showFilterList = true" @blur="handleBlur" ref="searchInput" />
          <image src="/static/search.svg" class="imagestyle" @click.stop="toggleFilterList"></image>

          <!-- 筛选列表（搜索框下方展开） -->
          <view class="filter-list" v-show="showFilterList" ref="filterList">
            <view class="filter-item" v-for="(item, index) in filteredProjects" :key="index" @click="selectProject(item)">
              {{ item }}
            </view>
          </view>
        </view>
      </view>

      <!-- 日报日期 -->
      <view class="partname">
        <text class="report-">日报日期</text>
        <!-- 自定义日期选择器 -->
        <view class="part-item" @click="openDatePicker">
          <input type="text" placeholder="" class="inputstyle" v-model="selectedDate" readonly />
          <image src="/static/calendar.svg" mode="widthFix" class="imagestyle"></image>
        </view>

        <!-- 遮罩层 -->
        <view class="custom-date-picker-mask" v-if="showDatePicker" @click="closeDatePicker"></view>

        <!-- 自定义日期选择器弹窗 -->
        <view class="custom-date-picker" v-if="showDatePicker">
          <view class="cdp-header">
            <text class="cdp-header-date">{{ currentYear }}年</text>
            <text class="cdp-header-date">{{ currentMonth }}月{{ currentDay }}日 周{{ weekDay }}</text>
          </view>

          <view class="cdp-nav">
            <text class="cdp-nav-btn" @click="prevMonth">＜</text>
            <text class="cdp-nav-text">{{ displayYear }}年{{ displayMonth }}月</text>
            <text class="cdp-nav-btn" @click="nextMonth">＞</text>
          </view>

          <view class="cdp-week">
            <text class="cdp-week-item" v-for="day in weekDays" :key="day">{{ day }}</text>
          </view>

          <view class="cdp-days">
            <view class="cdp-day-item" v-for="(day, index) in days" :key="index" :class="{ 'disabled': !day.valid, 'active': day.active }" @click="selectDay(day)">
              <text v-if="day.value">{{ day.value }}</text>
            </view>
          </view>

          <view class="cdp-footer">
            <text class="cdp-footer-btn" @click="closeDatePicker">取消</text>
            <text class="cdp-footer-btn confirm" @click="confirmDate">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 市政表读数数据模块 -->
   <view class="partitem">
      <view class="project-item">
        <h3 class="title-text">市政表读数数据</h3>
      </view>
      <view class="item-data" v-for="(meter, index) in meterList" :key="index" v-show="seedata">
        <view class="meter-info">
          <view class="meter-name">{{ meter.name }}</view>
          <view class="last-reading">上期读数: {{ meter.lastReading }}</view>
          <view class="upload-img-wrap">
            <image src="/static/camera.svg" mode="widthFix" class="cameraimage"></image>
            <text class="upload-text">上传图片</text>
          </view>
        </view>
        <input type="text" class="inputdata" v-model="meter.currentValue" placeholder="请输入当前读数"/>
      </view>
    </view>

    <!-- 今日水表备注模块 -->
	<view class="partitem">
	  <view class="project-item">
		<h3 class="title-text">今日水表备注</h3>
	  </view>
	  <view class="form-item">
		<!-- 绑定 v-model 并监听输入事件 -->
		<textarea v-model="waterMeterRemark" value="继续观察" maxlength="500" class="textarea-style" @input="updateWaterMeterCount"></textarea>
		<!-- 动态显示当前字数 -->
		<text class="count">{{ currentLength }}/500</text>
	  </view>
	</view>

    <!-- 日报图片模块 -->
    <view class="partitem">
      <view class="project-item">
        <h3 class="title-text">日报图片</h3>
      </view>
      <view v-for="(item, index) in selectedImages" :key="index" class="image-item">
        <image :src="item.path" class="selected-image" mode="aspectFill" />
        <input type="text" placeholder="添加图片备注" v-model="item.remark" class="remark-input" />
        <view class="delete-btn" @click="deleteImage(index)">
          <text class="delete-icon">×</text>
        </view>
      </view>
	  
      <uni-file-picker ref="filePicker" mode="upload" @select="onImageSelect" file-mediatype="image"
	  :limit="10" @progress="onProgress" @success="onSuccess" @fail="onFail">
        <view class="upload-area">
          <image src="/static/camera.svg" mode="widthFix" class="upload-icon" />
          <text class="upload-text">上传日报图片</text>
        </view>
      </uni-file-picker>
    </view>

	<view class="partitemend">
	  <view class="project-item">
		<h3 class="title-text">今日日报备注</h3>
	  </view>
	  <view class="form-item">
		<!-- 绑定 v-model 并监听输入事件 -->
		<textarea v-model="dailyReportRemark" value="今日抄表记录并分析用水情况，继续观察" maxlength="500" class="textarea-style" @input="updateReportCount"></textarea>
		<!-- 动态显示当前字数 -->
		<text class="count">{{ reportLength }}/500</text>
	  </view>
	</view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 项目选项数据
const projectOptions = ref([
  "百色市百色中学",
  "玉林实验中学",
  "广西现代职业技术学院",
  "广西机电工程学校",
  "钦州幼儿师范高等专科学校",
  "全部项目",
  "广西医科大学",
  "南宁理工学院",
  "明阳中学"
]);

// 在响应式数据部分添加
const meterList = ref([
  { name: '市政表1', lastReading: 11475, currentValue: '' },
  { name: '市政表2', lastReading: 747965, currentValue: '' },
  { name: '市政表3', lastReading: 25403, currentValue: '' },
  { name: '市政表4', lastReading: 40254, currentValue: '' }
]);

// 响应式数据
const searchKeyword = ref('');
const showFilterList = ref(false);
const selectedProject = ref('');
const filterList = ref(null);
const searchInput = ref(null);
const seedata = ref(false);
const readnumber = ref(''); // 可根据实际初始化，比如从接口获取

// 日期选择相关响应式数据
const showDatePicker = ref(false);
const selectedDate = ref('');
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
const currentDate = ref(new Date());
const displayDate = ref(new Date());
const tempSelectedDate = ref(null);

// 图片上传相关响应式数据
const selectedImages = ref([]);

// 计算属性
const currentYear = computed(() => currentDate.value.getFullYear());
const currentMonth = computed(() => currentDate.value.getMonth() + 1);
const currentDay = computed(() => currentDate.value.getDate());
const weekDay = computed(() => weekDays[currentDate.value.getDay()]);

const displayYear = computed(() => displayDate.value.getFullYear());
const displayMonth = computed(() => displayDate.value.getMonth() + 1);

const days = computed(() => {
  const year = displayDate.value.getFullYear();
  const month = displayDate.value.getMonth();
  const today = new Date();

  // 当月第一天
  const firstDay = new Date(year, month, 1);
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0);
  // 上个月最后几天
  const prevLastDay = new Date(year, month, 0).getDate();
  // 当月第一天是周几
  const firstDayOfWeek = firstDay.getDay();

  const daysArray = [];

  // 添加上个月的几天
  for (let i = firstDayOfWeek; i > 0; i--) {
    daysArray.push({
      value: prevLastDay - i + 1,
      valid: false,
      date: new Date(year, month - 1, prevLastDay - i + 1)
    });
  }

  // 添加当月的天数
  for (let i = 1; i <= lastDay.getDate(); i++) {
    const date = new Date(year, month, i);
    daysArray.push({
      value: i,
      valid: true,
      date: date,
      active: tempSelectedDate.value? date.toDateString() === tempSelectedDate.value.toDateString() : date.toDateString() === today.toDateString()
    });
  }

  // 添加下个月的几天（补齐42个格子）
  const totalCells = 42;
  const nextDays = totalCells - daysArray.length;
  for (let i = 1; i <= nextDays; i++) {
    daysArray.push({
      value: i,
      valid: false,
      date: new Date(year, month + 1, i)
    });
  }

  return daysArray;
});

// 实时过滤项目
const filteredProjects = computed(() => {
  return projectOptions.value.filter(item => item.toLowerCase().includes(searchKeyword.value.toLowerCase()));
});

// 切换筛选列表显示
const toggleFilterList = (e) => {
  e.stopPropagation();
  showFilterList.value =!showFilterList.value;
};

// 处理搜索框失焦
const handleBlur = (e) => {
  setTimeout(() => {
    if (!document.activeElement ||!document.activeElement.closest('.select-container')) {
      showFilterList.value = false;
    }
  }, 0);
};

// 点击筛选项
const selectProject = (item) => {
  selectedProject.value = item;
  searchKeyword.value = item;
  showFilterList.value = false;
  seedata.value = true;
};

// 日期选择器操作
const openDatePicker = () => {
  showDatePicker.value = true;
  displayDate.value = new Date(currentDate.value);
  tempSelectedDate.value = new Date(currentDate.value);
};

const closeDatePicker = () => {
  showDatePicker.value = false;
};

const prevMonth = () => {
  displayDate.value = new Date(
    displayDate.value.getFullYear(),
    displayDate.value.getMonth() - 1,
    1
  );
};

const nextMonth = () => {
  displayDate.value = new Date(
    displayDate.value.getFullYear(),
    displayDate.value.getMonth() + 1,
    1
  );
};

const selectDay = (day) => {
  if (!day.valid) return;
  tempSelectedDate.value = new Date(day.date);

  // 更新当前显示的日期
  currentDate.value = new Date(day.date);
  selectedDate.value = formatDate(currentDate.value);
};

const confirmDate = () => {
  showDatePicker.value = false;
};

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};




// 今日水表备注
const waterMeterRemark = ref('继续观察');
const currentLength = ref(waterMeterRemark.value.length); 

// 今日日报备注
const dailyReportRemark = ref('今日抄表记录并分析用水情况，继续观察');
const reportLength = ref(dailyReportRemark.value.length);

// 更新水表备注字数
const updateWaterMeterCount = () => {
  currentLength.value = waterMeterRemark.value.length;
};

// 更新日报备注字数
const updateReportCount = () => {
  reportLength.value = dailyReportRemark.value.length;
};


// 图片选择回调
const onImageSelect = (event) => {
  const tempFiles = event.tempFiles;
  tempFiles.forEach((file) => {
    // 过滤掉文件名显示，只处理图片路径和备注相关
    selectedImages.value.push({
      path: file.path,
      remark: '',
      // 保留文件原始信息，但不显示文件名
      fileInfo: file
    });
  });
};

// 删除图片
const deleteImage = (index) => {
  // 显示确认对话框
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        selectedImages.value.splice(index, 1);
      }
    }
  });
};

// 上传进度回调（可选）
const onProgress = (event) => {
  console.log('上传进度:', event.progress);
};

// 上传成功回调（可选）
const onSuccess = (event) => {
  console.log('上传成功:', event);
};

// 上传失败回调（可选）
const onFail = (event) => {
  console.log('上传失败:', event);
};

// 初始化
onMounted(() => {
  selectedDate.value = formatDate(currentDate.value);
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  background-color: #e6e6e6;
  min-height: 100vh;
  padding: 20rpx;
}

.project-item {
  padding-left: 12rpx;
  position: relative;
  margin-left: 12rpx;
}

.project-item h3 {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.project-item::before {
  content: "";
  display: inline-block;
  width: 8rpx; 
  height: 40rpx; 
  background-color: #409eff; 
  position: absolute;
  left: -1.5%;
  top: 50%;
  transform: translateY(-50%); 
}

.partitem {
  display: flex;
  flex-direction: column;
  background-color: #fcfcfc;
  padding: 30rpx 20rpx;
  border-radius: 10rpx;
  margin: 10rpx 0;
}

.partname {
  font-size: 28rpx;
  margin-top: 20rpx;
  color: #555;
  font-weight: 500;
}

.select-container,
.part-item {
  position: relative;
  display: flex;
  align-items: center;
  margin-top: 15rpx;
}

.inputstyle {
  background-color: #f8f8f8;
  border-radius: 12rpx;
  height: 80rpx;
  padding: 0 25rpx;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #eee;
  flex: 1;
  box-sizing: border-box;
}

.imagestyle {
  width: 36rpx;
  height: 36rpx;
  position: absolute; 
  right: 25rpx; 
  top: 50%;
  transform: translateY(-50%);
}

.filter-list {
  position: absolute;
  top: 100%; 
  left: 0;
  width: 100%;
  max-height: 400rpx;
  overflow-y: auto;
  background-color: #fff;
  border: 1rpx solid #e8e8e8;
  border-radius: 12rpx;
  margin-top: 10rpx;
  z-index: 100;
  box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.1);
}

.filter-item {
  padding: 22rpx 25rpx;
  font-size: 28rpx;
  color: #333;
}

.filter-item:last-child {
  border-bottom: none;
}

.filter-item:active {
  background-color: #f9f9f9;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-top: 15rpx;
}

.textarea-style {
  width: 100%;
  min-height: 180rpx;
  padding: 15rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  resize: none;
  border: 1rpx solid #eee;
  color: #333;
  box-sizing: border-box;
}

.count {
  align-self: left;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 50rpx 0;
  gap: 20rpx;
  margin-top: 20rpx;
  border: 1rpx dashed #ddd;
}

.upload-area .upload-icon {
  width: 50rpx;
  height: 50rpx;
}

.upload-area .upload-text {
  font-size: 28rpx;
  color: #888;
}

.custom-date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 998;
}

.custom-date-picker {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 650rpx;
  background-color: #fff;
  border-radius: 25rpx;
  z-index: 999;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.cdp-header {
  background-color: #009688;
  color: #fff;
  padding: 30rpx 0;
  text-align: center;
}

.cdp-header-date {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  line-height: 1.6;
}

.cdp-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.cdp-nav-btn {
  font-size: 40rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #009688;
  font-weight: bold;
}

.cdp-nav-text {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.cdp-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  padding: 20rpx 0;
  background-color: #f5f5f5;
}

.cdp-week-item {
  text-align: center;
  font-size: 28rpx;
  color: #666;
}

.cdp-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
  padding: 20rpx;
}

.cdp-day-item {
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
  color: #333;
  border-radius: 50%;
}

.cdp-day-item.active {
  background-color: #009688;
  color: #fff;
  font-weight: bold;
}

.cdp-day-item.disabled {
  color: #ccc;
}

.cdp-footer {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eee;
  padding: 25rpx 40rpx;
}

.cdp-footer-btn {
  font-size: 32rpx;
  padding: 15rpx 60rpx;
  border-radius: 50rpx;
  color: #666;
  border: 1rpx solid #ddd;
}

.cdp-footer-btn.confirm {
  background-color: #009688;
  color: #fff;
  border: none;
}

.item-data {
  padding: 20rpx;
  align-items: center; 
  background-color: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.meter-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.meter-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  width: 140rpx;
  align-items: left;
}

.last-reading {
  font-size: 24rpx;
  color: #999;
  align-items: center;
  font-weight: bold;
}

.upload-img-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8rpx;
  width: 140rpx;
  background-color: #fff;
  object-fit: cover;
  padding: 15rpx;
  border-radius: 30rpx;
}

.inputdata {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx 0;
  width: 100%;
}

.cameraimage {
  width: 32rpx;
  height: 32rpx;
  vertical-align: middle;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.image-item {
  display: flex;
  align-items: center;
  margin-top: 15rpx;
  gap: 15rpx;
  padding: 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  position: relative;
}

.selected-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.remark-input {
   flex: 1;
    height: 180rpx;
    padding: 10rpx 15rpx; /* 减少上下内边距，使文字上移 */
    background-color: #fff;
    border-radius: 8rpx;
    border: 1rpx solid #eee;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
    line-height: 1.2; /* 调整行高，使文字排列更紧凑 */
}

.delete-btn {
  position: absolute;
  right: 15rpx;
  top: 15rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.delete-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

::v-deep .icon-del-box,
::v-deep .icon-files {
  display: none !important;
}

/* 隐藏文件名和其他文件信息 */
::v-deep .files__name,
::v-deep .files__size,
::v-deep .files__progress {
  display: none !important;
}

/* 隐藏 uni-file-picker__lists-box 元素 */
::v-deep .uni-file-picker__lists-box {
  display: none !important;
}

/* 调整上传区域样式，避免因隐藏元素导致布局错乱 */
::v-deep .uni-file-picker__upload {
  padding: 0 !important;
  margin: 0 !important;
}

/* 如果需要完全隐藏文件列表容器 */
::v-deep .uni-file-picker__list {
  display: none !important;
}


@media (max-width: 375px) {
  .cdp-nav-text {
    font-size: 30rpx;
  }
  
  .cdp-day-item {
    height: 70rpx;
    font-size: 28rpx;
  }
  
  .remark-input {
    height: 160rpx;
  }
  
  .selected-image {
    width: 140rpx;
    height: 140rpx;
  }
}
.partitemend{
	display: flex;
	flex-direction: column;
	background-color: #fcfcfc;
	padding: 30rpx 20rpx;
	border-radius: 10rpx;
	margin-top: 10rpx;
	margin-bottom: 100rpx;
}
</style>